/*
 * @Author: crissu 13750782397@163.com
 * @Date: 2024-05-30 01:09:29
 * @LastEditors: crissu 13750782397@163.com
 * @LastEditTime: 2024-05-30 01:11:32
 * @FilePath: /try_concurrence/DeadlocksLivelocksAndStarvation/tryDeadlocks.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package deadlockslivelocksandstarvation

import (
	"fmt"
	"sync"
	"time"
)

type value struct {
	mu    sync.Mutex
	value int
}

func TryDeadlocks() {
	var wg sync.WaitGroup
	printSum := func(v1, v2 *value) {
		defer wg.Done()
		v1.mu.Lock()
		defer v1.mu.Unlock()

		// deadlock
		time.Sleep(2 * time.Second)
		v2.mu.Lock()
		defer v2.mu.Unlock()

		fmt.Printf("sum=%v\n", v1.value+v2.value)
	}

	var a, b value
	wg.Add(2)
	go printSum(&a, &b)
	go printSum(&b, &a)

	wg.Wait()
}
